package com.master.demo.generator.util;

import cn.hutool.core.text.StrFormatter;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.master.demo.generator.config.GenConstants;
import com.master.demo.generator.pojo.entity.GenTable;
import com.master.demo.generator.pojo.entity.GenTableColumn;
import com.master.common.constant.StringPoolConstant;
import com.master.common.utils.DateUtil;
import com.master.common.utils.StringUtil;
import com.master.common.validator.ValidatorUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.velocity.VelocityContext;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 模板处理工具类
 *
 * @author: Yang
 * @date: 2023/01/31
 * @version: 1.0.0
 * https://www.panday94.xyz
 * Copyright Ⓒ 2023 熊扬软件开发工作室 Limited All rights reserved.
 */
public class VelocityUtils {

    /**
     * 项目空间路径
     */
    private static final String PROJECT_PATH = "main/java";

    /**
     * mybatis空间路径
     */
    private static final String MYBATIS_PATH = "main/resources/mapper";

    /**
     * 默认上级菜单，系统工具
     */
    private static final String DEFAULT_PARENT_MENU_ID = "3";

    /**
     * 设置模板变量信息
     *
     * @return 模板列表
     */
    public static VelocityContext prepareContext(GenTable genTable) {
        String packageName = genTable.getPackageName();
        String className = genTable.getClassName();
        String moduleName = genTable.getModuleName();
        String businessName = genTable.getBusinessName();
        String functionName = genTable.getFunctionName();
        String tableName = genTable.getTableName();
        String tplCategory = genTable.getTplCategory();

        List<GenTableColumn> columns = genTable.getColumns();
        List<String> importList = getImportList(genTable);
        List<String> importDTOList = new ArrayList<>();

        VelocityContext velocityContext = new VelocityContext();
        velocityContext.put("table", genTable);
        velocityContext.put("packageName", packageName);
        velocityContext.put("ClassName", className);
        velocityContext.put("moduleName", moduleName);
        velocityContext.put("businessName", businessName);
        velocityContext.put("functionName", functionName);
        velocityContext.put("tableName", tableName);
        velocityContext.put("BusinessName", className);
        velocityContext.put("className", StringUtils.uncapitalize(className));
        velocityContext.put("vueFileName", GenUtils.convertDashName(tableName));
        velocityContext.put("author", genTable.getFunctionAuthor());
        velocityContext.put("pkColumn", genTable.getPkColumn());
        velocityContext.put("superEntityClass", genTable.getSuperEntityClass());
        velocityContext.put("superControllerClass", genTable.getSuperControllerClass());
        velocityContext.put("baseEntity", isBaseEntity(columns));
        velocityContext.put("basePackage", getPackagePrefix(packageName));
        velocityContext.put("controllerPath", GenUtils.convertDashName(tableName));
        velocityContext.put("permissionPrefix", getPermissionPrefix(tableName));
        velocityContext.put("tplCategory", tplCategory);
        velocityContext.put("importList", importList);
        velocityContext.put("dicts", getDicts(genTable));
        velocityContext.put("columns", columns);
        String fieldNames = getFieldNames(columns);
        velocityContext.put("fieldNames", fieldNames);
        velocityContext.put("isCreateUser", fieldNames.contains("create_user"));
        velocityContext.put("isUpdateUser", fieldNames.contains("update_user"));
        velocityContext.put("versionFieldName", GenConstants.VERSION_FIELD_NAME);
        velocityContext.put("logicDeleteFieldName", GenConstants.LOGIC_DELETE_FIELD_NAME);
        velocityContext.put("datetime", DateUtil.getCurrentDate());

        if (importList.contains("java.time.LocalDateTime")) {
            importDTOList.add("java.time.LocalDateTime");
        }
        if (importList.contains("java.math.BigDecimal")) {
            importDTOList.add("java.math.BigDecimal");
        }
        velocityContext.put("importDTOList", importDTOList);
        setMenuVelocityContext(velocityContext, genTable);
        if (GenConstants.TPL_TREE.equals(tplCategory)) {
            setTreeVelocityContext(velocityContext, genTable);
        }
        if (GenConstants.TPL_SUB.equals(tplCategory)) {
            setSubVelocityContext(velocityContext, genTable);
        }
        return velocityContext;
    }

    /**
     * 获取字段列表
     *
     * @param columns 字段信息
     * @return
     */
    private static String getFieldNames(List<GenTableColumn> columns) {
        List<String> strings = columns.stream().map(v -> v.getColumnName()).collect(Collectors.toList());
        StringJoiner stringJoiner = new StringJoiner(StringPoolConstant.COMMA + StringPoolConstant.SPACE);
        strings.forEach(v -> stringJoiner.add("t." + v));
        return stringJoiner.toString();
    }

    /**
     * 是否继承BaseEntity
     *
     * @param columns 字段信息
     * @return
     */
    private static Boolean isBaseEntity(List<GenTableColumn> columns) {
        List<String> strings = columns.stream().map(v -> v.getJavaField()).collect(Collectors.toList());
        return strings.containsAll(Arrays.asList(GenConstants.BASE_ENTITY));
    }

    /**
     * 获取包前缀
     *
     * @param packageName 包名称
     * @return 包前缀名称
     */
    private static String getPackagePrefix(String packageName) {
        int lastIndex = packageName.lastIndexOf(StringPoolConstant.DOT);
        return StringUtils.substring(packageName, 0, lastIndex);
    }

    /**
     * 根据列类型获取字典组
     *
     * @param genTable 业务表对象
     * @return 返回字典组
     */
    private static String getDicts(GenTable genTable) {
        List<GenTableColumn> columns = genTable.getColumns();
        Set<String> dicts = new HashSet<>();
        addDicts(dicts, columns);
        if (ValidatorUtil.isNotNull(genTable.getSubTable())) {
            List<GenTableColumn> subColumns = genTable.getSubTable().getColumns();
            addDicts(dicts, subColumns);
        }
        return StringUtils.join(dicts, StringPoolConstant.COMMA + StringPoolConstant.EMPTY);
    }

    private static void setMenuVelocityContext(VelocityContext context, GenTable genTable) {
        String options = genTable.getOptions();
        JSONObject paramsObj = JSON.parseObject(options);
        String parentId = getParentMenuId(paramsObj);
        context.put(GenConstants.PARENT_ID, parentId);
    }

    private static void setTreeVelocityContext(VelocityContext context, GenTable genTable) {
        String options = genTable.getOptions();
        JSONObject paramsObj = JSON.parseObject(options);
        String treeCode = getTreecode(paramsObj);
        String treeParentCode = getTreeParentCode(paramsObj);
        String treeName = getTreeName(paramsObj);

        context.put("treeCode", treeCode);
        context.put("treeParentCode", treeParentCode);
        context.put("treeName", treeName);
        context.put("expandColumn", getExpandColumn(genTable));
        if (paramsObj.containsKey(GenConstants.TREE_PARENT_CODE)) {
            context.put("tree_parent_code", paramsObj.getString(GenConstants.TREE_PARENT_CODE));
        }
        if (paramsObj.containsKey(GenConstants.TREE_NAME)) {
            context.put("tree_name", paramsObj.getString(GenConstants.TREE_NAME));
        }
    }

    private static void setSubVelocityContext(VelocityContext context, GenTable genTable) {
        GenTable subTable = genTable.getSubTable();
        String subTableName = genTable.getSubTableName();
        String subTableFkName = genTable.getSubTableFkName();
        String subClassName = genTable.getSubTable().getClassName();
        String subTableFkClassName = StringUtil.convertToCamelCase(subTableFkName);

        context.put("subTable", subTable);
        context.put("subTableName", subTableName);
        context.put("subTableFkName", subTableFkName);
        context.put("subTableFkClassName", subTableFkClassName);
        context.put("subTableFkclassName", StringUtils.uncapitalize(subTableFkClassName));
        context.put("subClassName", subClassName);
        context.put("subclassName", StringUtils.uncapitalize(subClassName));
        context.put("subImportList", getImportList(genTable.getSubTable()));
    }


    /**
     * 获取模板信息
     *
     * @return 模板列表
     */
    public static List<String> getTemplateList(String tplCategory) {
        List<String> templates = new ArrayList<>();
        templates.add("vm/java/controller.java.vm");
        templates.add("vm/java/entity.java.vm");
        templates.add("vm/java/command.java.vm");
        templates.add("vm/java/dto.java.vm");
        templates.add("vm/java/vo.java.vm");
        templates.add("vm/java/service.java.vm");
        templates.add("vm/java/serviceImpl.java.vm");
        templates.add("vm/java/mapper.java.vm");
        templates.add("vm/java/mapper.xml.vm");
        templates.add("vm/sql/sql.vm");
        templates.add("vm/vue/api.js.vm");
        if (GenConstants.TPL_CRUD.equals(tplCategory)) {
            templates.add("vm/vue/index.vue.vm");
        } else if (GenConstants.TPL_TREE.equals(tplCategory)) {
            templates.add("vm/vue/index-tree.vue.vm");
        } else if (GenConstants.TPL_SUB.equals(tplCategory)) {
            templates.add("vm/vue/index.vue.vm");
            templates.add("vm/java/sub-entity.java.vm");
        }
        return templates;
    }

    /**
     * 获取文件名
     */
    public static String getFileName(String template, GenTable genTable) {
        // 文件名称
        String fileName = StringPoolConstant.EMPTY;
        // 包路径
        String packageName = genTable.getPackageName();
        // 模块名
        String moduleName = genTable.getModuleName();
        // 大写类名
        String className = genTable.getClassName();
        // 业务名称
        String businessName = genTable.getBusinessName();
        // vue文件名
        String vueFileName = GenUtils.convertDashName(genTable.getTableName());

        String javaPath = PROJECT_PATH + StringPoolConstant.SLASH + StringUtils.replace(packageName, StringPoolConstant.DOT, StringPoolConstant.SLASH);
        String mybatisPath = MYBATIS_PATH;
        String vuePath = "vue";

        if (template.contains("controller.java.vm")) {
            fileName = StrFormatter.format("{}/controller/{}/{}Controller.java", javaPath, moduleName, className);
        } else if (template.contains("entity.java.vm")) {
            fileName = StrFormatter.format("{}/{}/pojo/entity/{}.java", javaPath, moduleName, className);
        } else if (template.contains("command.java.vm")) {
            fileName = StrFormatter.format("{}/{}/pojo/command/{}Command.java", javaPath, moduleName, className);
        } else if (template.contains("dto.java.vm")) {
            fileName = StrFormatter.format("{}/{}/pojo/dto/{}DTO.java", javaPath, moduleName, className);
        } else if (template.contains("vo.java.vm")) {
            fileName = StrFormatter.format("{}/{}/pojo/vo/{}VO.java", javaPath, moduleName, className);
        } else if (template.contains("service.java.vm")) {
            fileName = StrFormatter.format("{}/{}/service/I{}Service.java", javaPath, moduleName, className);
        } else if (template.contains("serviceImpl.java.vm")) {
            fileName = StrFormatter.format("{}/{}/service/impl/{}ServiceImpl.java", javaPath, moduleName, className);
        } else if (template.contains("mapper.java.vm")) {
            fileName = StrFormatter.format("{}/{}/mapper/{}Mapper.java", javaPath, moduleName, className);
        } else if (template.contains("mapper.xml.vm")) {
            fileName = StrFormatter.format("{}/{}/{}Mapper.xml", mybatisPath, moduleName, className);
        } else if (template.contains("sql.vm")) {
            fileName = StrFormatter.format("{}/sql/{}/{}.sql", vuePath, moduleName, StringUtils.uncapitalize(className));
        } else if (template.contains("api.js.vm")) {
            fileName = StrFormatter.format("{}/api/{}/{}.js", vuePath, moduleName, StringUtils.uncapitalize(className));
        } else if (template.contains("index.vue.vm")) {
            fileName = StrFormatter.format("{}/views/{}/{}/index.vue", vuePath, moduleName, vueFileName);
        } else if (template.contains("index-tree.vue.vm")) {
            fileName = StrFormatter.format("{}/views/{}/{}/index.vue", vuePath, moduleName, vueFileName);
        }
        return fileName;
    }


    /**
     * 根据列类型获取导入包
     *
     * @param genTable 业务表对象
     * @return 返回需要导入的包列表
     */
    private static List<String> getImportList(GenTable genTable) {
        List<GenTableColumn> columns = genTable.getColumns();
        GenTable subGenTable = genTable.getSubTable();
        List<String> importList = new ArrayList<>();

        if (genTable.isLombok()) {
            importList.add("lombok.Data");
            importList.add("lombok.Builder");
            importList.add("lombok.AllArgsConstructor");
            importList.add("lombok.NoArgsConstructor");
            importList.add("lombok.EqualsAndHashCode");
            importList.add("lombok.experimental.Accessors");
        }
        if (ValidatorUtil.isNull(genTable.getSuperEntityClass())) {
            importList.add("java.io.Serializable");
            importList.add("com.baomidou.mybatisplus.annotation.IdType");
            importList.add("com.baomidou.mybatisplus.annotation.TableIde");
        } else {
            importList.add(genTable.getSuperEntityClass());
        }
        if (genTable.isSwagger()) {
            importList.add("io.swagger.annotations.ApiModel");
            importList.add("io.swagger.annotations.ApiModelProperty");
        }
        if (ValidatorUtil.isNotNull(subGenTable)) {
            importList.add("java.util.List");
        }
        importList.add("com.baomidou.mybatisplus.annotation.TableName;");
        for (GenTableColumn column : columns) {
            if (ValidatorUtil.isNotNull(genTable.getSuperEntityClass()) && column.isSuperColumn()) {
                continue;
            }

            if (GenConstants.LOGIC_DELETE_FIELD_NAME.equals(column.getColumnName())) {
                importList.add("com.baomidou.mybatisplus.annotation.TableLogic");
            }
            if (GenConstants.VERSION_FIELD_NAME.equals(column.getColumnName())) {
                importList.add("com.baomidou.mybatisplus.annotation.Version;");
            }

            if (GenConstants.TYPE_DATE.equals(column.getJavaType())) {
                importList.add("java.time.LocalDateTime");
            } else if (GenConstants.TYPE_BIGDECIMAL.equals(column.getJavaType())) {
                importList.add("java.math.BigDecimal");
            }
        }
        return importList.stream().sorted().distinct().collect(Collectors.toList());
    }

    /**
     * 添加字典列表
     *
     * @param dicts   字典列表
     * @param columns 列集合
     */
    public static void addDicts(Set<String> dicts, List<GenTableColumn> columns) {
        for (GenTableColumn column : columns) {
            if (!column.isSuperColumn() && ValidatorUtil.isNotNull(column.getDictType()) && StringUtils.equalsAny(
                    column.getHtmlType(), new String[]{GenConstants.HTML_SELECT, GenConstants.HTML_RADIO, GenConstants.HTML_CHECKBOX})) {
                dicts.add(StringPoolConstant.SINGLE_QUOTE + column.getDictType() + StringPoolConstant.SINGLE_QUOTE);
            }
        }
    }

    /**
     * 获取权限前缀
     *
     * @param tableName 表名
     * @return 返回权限前缀
     */
    private static String getPermissionPrefix(String tableName) {
        return tableName.replace(StringPoolConstant.UNDERSCORE, StringPoolConstant.COLON);
    }

    /**
     * 获取上级菜单ID字段
     *
     * @param paramsObj 生成其他选项
     * @return 上级菜单ID字段
     */
    private static String getParentMenuId(JSONObject paramsObj) {
        if (ValidatorUtil.isNotNull(paramsObj) && paramsObj.containsKey(GenConstants.PARENT_ID)
                && ValidatorUtil.isNotNull(paramsObj.getString(GenConstants.PARENT_ID))) {
            return paramsObj.getString(GenConstants.PARENT_ID);
        }
        return DEFAULT_PARENT_MENU_ID;
    }

    /**
     * 获取树编码
     *
     * @param paramsObj 生成其他选项
     * @return 树编码
     */
    private static String getTreecode(JSONObject paramsObj) {
        if (paramsObj.containsKey(GenConstants.TREE_CODE)) {
            return StringUtil.toCamelCase(paramsObj.getString(GenConstants.TREE_CODE));
        }
        return StringUtils.EMPTY;
    }

    /**
     * 获取树父编码
     *
     * @param paramsObj 生成其他选项
     * @return 树父编码
     */
    private static String getTreeParentCode(JSONObject paramsObj) {
        if (paramsObj.containsKey(GenConstants.TREE_PARENT_CODE)) {
            return StringUtil.toCamelCase(paramsObj.getString(GenConstants.TREE_PARENT_CODE));
        }
        return StringUtils.EMPTY;
    }

    /**
     * 获取树名称
     *
     * @param paramsObj 生成其他选项
     * @return 树名称
     */
    private static String getTreeName(JSONObject paramsObj) {
        if (paramsObj.containsKey(GenConstants.TREE_NAME)) {
            return StringUtil.toCamelCase(paramsObj.getString(GenConstants.TREE_NAME));
        }
        return StringUtils.EMPTY;
    }

    /**
     * 获取需要在哪一列上面显示展开按钮
     *
     * @param genTable 业务表对象
     * @return 展开按钮列序号
     */
    private static int getExpandColumn(GenTable genTable) {
        String options = genTable.getOptions();
        JSONObject paramsObj = JSON.parseObject(options);
        String treeName = paramsObj.getString(GenConstants.TREE_NAME);
        int num = 0;
        for (GenTableColumn column : genTable.getColumns()) {
            if (column.isList()) {
                num++;
                String columnName = column.getColumnName();
                if (columnName.equals(treeName)) {
                    break;
                }
            }
        }
        return num;
    }

}
